<template>
  <el-dialog title="分配权限" :visible="showDialog" @close="closeFn">
    <!-- 权限列表 -->
    <!-- show-checkbox: 显示复选框
         node-key：每个树节点用来作为唯一标识的属性，整棵树应该是唯一的
         default-expand-all：默认展开所有节点
         check-strictly：为ture的时候，取消复选框的父子框关联
         -->
    <el-tree ref="tree" node-key="id" show-checkbox :data="permList" :props="{label:'name'}" default-expand-all check-strictly />
    <el-row type="flex" justify="center">
      <el-button type="primary" size="small" @click="confirmFn">确认</el-button>
      <el-button size="small" @click="closeFn">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissions } from '@/api/permission'
import { listToTree } from '@/utils/index'
import { getRoleDetailById, assignPerm } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permList: [],
      permIds: [],
      roleId: ''
    }
  },
  async created() {
    // 获取所有权限列表
    const res = await getPermissions()
    this.permList = listToTree(res, '0')
  },
  methods: {
    // 分配权限  确定按钮
    async confirmFn() {
      // 获取 选中选项的数据
      const permIds = this.$refs.tree.getCheckedKeys()
      // 调用接口实现分配权限
      await assignPerm({
        id: this.roleId, // 角色Id
        permIds
      })
      // 关闭弹窗
      this.closeFn()
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空默认选中的选项
      this.permIds = []
      this.$refs.tree.setCheckedKeys(this.permIds)
    },
    // 获取角色默认 的权限列表
    async getPermIds(id) {
      // 添加loading效果
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.5)'
      })
      // 保存角色id
      this.roleId = id
      const res = await getRoleDetailById(id)
      // 获取到角色的默认权限列表（由id构成的数组）
      this.permIds = res.permIds
      // 权限回显
      this.$refs.tree.setCheckedKeys(this.permIds)
      //  关闭loading
      loading.close()
    }
  }
}
</script>

<style>
.el-loading-mask.is-fullscreen{
    z-index: 999999999 !important;
}
</style>
